package org.game.module.datingbo.handler;

import com.sojoys.artifact.manager.MessageManager;
import com.sojoys.artifact.tools.ToolError;
import org.cfg.DatingCfg;
import org.cfg.DatingRuleCfg;
import org.cfg.cache.DatingRuleCfgCache;
import org.constant.DatingConstant;
import org.error.GameErrorCode;
import org.game.constant.DatingTypeConstant;
import org.game.db.bean.CurrentScriptRecord;
import org.game.db.bean.Dating;
import org.game.db.bean.Player;
import org.game.db.bean.Role;
import org.game.db.cache.CurrentScriptRecordCache;
import org.game.db.cache.PlayerCache;
import org.game.db.cache.RoleCache;
import org.game.log.LogDating;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.DatingDsp;
import org.game.manager.DatingManager;
import org.game.module.datingbo.DatingBO;
import org.game.module.datingbo.DatingType;
import org.game.module.rolebo.RoleBO;
import org.game.msgBuilder.DatingMsgBuilder;
import org.game.protobuf.c2s.C2SDatingMsg;
import org.game.protobuf.s2c.S2CRoleMsg.RoleInfo;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.util.ProtoUnit;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by fxf on 2017/11/20.
 */
@DatingType(DatingTypeConstant.DATING_TYPE_MAIN)
public class MainDatingHandler extends AbstractDatingHandler {
    @Override
    public byte[] getScript(Player player, C2SDatingMsg.GetScriptMsg msg) {
        int roleId = msg.getRoleId();

        Role role = RoleCache.me().getByCidPlayerId(roleId,player.getId());


        // 获取主线剧本id
        int scriptId = getMainScriptId(player,role);
        ToolError.isAndTrue(GameErrorCode.MAIN_DATING_IS_NULL, scriptId == 0);

        // 筛选分支节点
        Map<Integer, List<Integer>> branchNodes = getScriptBranchNode(player, scriptId,msg);

        //获取起始节点
        int startNodeId = getStartNodeId(scriptId);

        createCurrentScriptRecord(player, scriptId, branchNodes, startNodeId, Arrays.asList(roleId));

        LogDating.me().log(player.getId(),getDatingType(),scriptId,role.getCid(), LogDsp.newBuilder(DatingDsp.GET_SCRIPT));
        player.getPlayerProxy().sendMsg(DatingBO.sendEveryDayScript,DatingMsgBuilder.getDatingScriptMsg(scriptId,null));

        return new byte[0];
    }

    /**
     * 获取主线剧本id
     */
    private int getMainScriptId(Player player,Role role) {
        if (role.getFavor() != 0 && !role.getRoleProxy().isCriticalPoint()){
            return 0;
        }
        List<DatingRuleCfg> ruleCfgList = DatingRuleCfgCache.me().getDatingRuleByRoleIdDatingType(role.getCid(),getDatingType());
        Dating dating = DatingManager.getDating(player);
        int scriptId = 0;
        for (DatingRuleCfg datingRuleCfg : ruleCfgList) {
            if (dating.getScriptIdList().contains(datingRuleCfg.getId())){
                continue;
            }
            if (datingRuleCfg.getEnterCondtionByType(DatingConstant.ENTER_CDTION_KEY_FAVOR) == role.getFavor()) {
                scriptId = datingRuleCfg.getId();
                break;
            }

        }
        return scriptId;
    }

    @Override
    protected void endDatingRecord(Player player, Dating dating, DatingCfg cfg,int roleCid,CurrentScriptRecord record) {
        super.endDatingRecord(player,dating,cfg,roleCid,record);
        Role role = RoleCache.me().getByCidPlayerId(roleCid,player.getId());
        role.setCriticalPoint(false);
        role.update();

        RoleInfo.Builder builder = RoleInfo.newBuilder();
		builder.setCt(ChangeType.UPDATE);
		builder.setId(Long.toString(role.getId()));
		builder.setCid(role.getCid());
		builder.setFavorCriticalPoint(role.getRoleProxy().isCriticalPoint());
		RoleInfo roleInfo = builder.build();
		player.getPlayerProxy().sendMsg(MessageManager.me().create(RoleBO.pushRole, ProtoUnit.toByte(roleInfo)));
    }

    @Override
    public boolean isFail(Player player, int roleCid, boolean isLastNode) {
        CurrentScriptRecord record = CurrentScriptRecordCache.me().getCurrentScriptRecordCacheProxy().getByPlayerIdDatingTypeRoleId(player.getId(), getDatingType(), roleCid);
        if (isLastNode) {
            DatingRuleCfg cfg = DatingRuleCfgCache.me().getById(record.getScriptId());
            for (Object o : cfg.getFailCondition().entrySet()) {
                Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) o;
                switch (entry.getKey()) {
                    case DatingConstant.FAIL_CDTION_SCORE: {
                        if (record.getScore() < entry.getValue()) {
                            return false;
                        }
                        break;
                    }
                }
            }
        } else {
            if (record.getScore() <= 0) {
                return true;
            }
        }
        return false;
    }
}
